package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.model.user.entity.ApUser;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * APP用户表(ApUser)表服务实现类
 *
 * @author makejava
 * @since 2023-06-21 17:46:48
 */
@Service("apUserService")
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Resource
    private ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //判断是正常登录还是匿名登录
        if(StringUtils.isNotEmpty(loginDto.getPhone())&&StringUtils.isNotEmpty(loginDto.getPassword())){
            //正常登录
            //根据电话号码查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //用户输入的密码进行MD5加盐解密
            String parsePassword = MD5Utils.encodeWithSalt(loginDto.getPassword(), apUser.getSalt());
            //与数据库密码比对是否正确
            if(!StringUtils.equals(parsePassword,apUser.getPassword())){
                //密码不正确，返回密码错误
                ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //密码比对成功
            //封装返回数据
            Map<String,Object> result =new HashMap<>();
            result.put("token",AppJwtUtil.getToken(apUser.getId()));
            apUser.setSalt(null);
            apUser.setPassword(null);
            result.put("user",apUser);
            return ResponseResult.okResult(result);

        }else{
            //匿名登录
            Map<String,Object> result=new HashMap<>();
            result.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(result);
        }
    }
}

